<template>
  <el-dialog :title="title" :visible.sync="visible" width="60%">
    <el-form :model="jobForm" label-width="120px">
      <el-form-item label="作业标题">
        <el-input
          v-model="jobForm.title"
          autocomplete="off"
          :disabled="!isEdit"
        />
      </el-form-item>
      <el-form-item v-if="!jobForm.isPublic" label="作业所属班级">
        <ClassSelect v-model="jobForm.gradeId" :is-edit="!isEdit" />
      </el-form-item>
      <el-form-item label="作业时间范围" prop="start">
        <el-date-picker
          v-model="jobForm.time"
          type="datetimerange"
          range-separator="至"
          value-format="yyyy-MM-ddTHH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="作业具体内容">
        <div id="quillEditorQiniu">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :accept="'image/*,video/*'"
            :show-file-list="false"
            :on-success="uploadEditorSuccess"
            :on-error="uploadEditorError"
            :before-upload="beforeEditorUpload"
            :headers="headers"
          >
          </el-upload>
          <quill-editor
            ref="myQuillEditor"
            v-model="jobForm.content"
            :options="editorOption"
            class="my-quill-editor"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
          />
        </div>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import ClassSelect from "@/components/ClassSelect";
import { getRole } from "@/utils/jwtUtils";
import { getToken } from "@/utils/auth";

export default {
  components: {
    ClassSelect,
    quillEditor,
  },
  props: {
    title: {
      type: String,
      default: "提示",
    },
    editType: {
      type: Number,
      default: 0,
    },
    value: {
      type: Boolean,
      default: false,
    },
    dialogData: {
      type: Object,
      default() {
        return {
          title: "",
          gradeId: "",
          content: "",
        };
      },
    },
    isEdit: {
      type: Boolean,
      default: true,
    },
    onConfirm: {
      type: Function,
      default: () => {},
    },
  },
  data() {
    return {
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/upload/image",
      roleEdit: false,
      jobForm: {
        time: [],
        title: "",
        gradeId: "",
        content: "",
      },
      visible: this.value,
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"],
              ["blockquote", "code-block"],
              [{ list: "ordered" }, { list: "bullet" }],
              [{ indent: "-1" }, { indent: "+1" }],
              [{ color: [] }, { background: [] }],
              ["image"],
              ["clean"],
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  document
                    .querySelector("#quillEditorQiniu .avatar-uploader input")
                    .click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
        placeholder: "请输入正文",
      },
    };
  },
  watch: {
    value(val) {
      this.visible = val;
    },
    isEdit(val) {
      this.isEdit = val;
    },
    dialogData(val) {
      console.log("dialogData", val);
      this.jobForm = val;
      if (val.startTime && val.endTime) {
        this.jobForm.time = [val.startTime, val.endTime];
      }
      console.log("jobForm", this.jobForm); 
      if (val.isPublic) {
        this.jobForm.isPublic = true;
      }
    },
    visible(val) {
      this.$emit("input", val);
    },
  },
  created() {
    const role = getRole();
    if (role === 3 && this.editType === 1) {
      this.jobForm.isPublic = true;
      this.roleEdit = true;
    }
  },
  methods: {
    //上传图片之前async
    beforeEditorUpload(res, file) {
      //显示上传动画
      this.quillUpdateImg = true;
      //  const res1 = await uploadImage()
      // this.$emit('before',res, file)
      console.log(res);
      console.log(file);
    },
    // 上传(文件)图片失败
    uploadEditorError(res, file) {
      //页面提示
      this.$message.error("上传图片失败");
      //取消上传动画
      this.quillUpdateImg = false;
    },
    // 上传图片成功
    uploadEditorSuccess(res, file) {
      // //拼接出上传的图片在服务器的完整地址
      let url = res.data;
      let type = url.substring(url.lastIndexOf(".") + 1);
      // 获取富文本组件实例
      let quill = this.$refs.myQuillEditor.quill;
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片||视频  res.info为服务器返回的图片地址
      if (type == "mp4" || type == "MP4") {
        window.jsValue = url;
        quill.insertEmbed(length, "video", url);
      } else {
        quill.insertEmbed(length, "image", url);
      }
      // 调整光标到最后
      quill.setSelection(length + 1);
      //取消上传动画
      this.quillUpdateImg = false;
    },
    handleCancel() {
      this.visible = false;
      if (this.editType === 1) {
        // 如果是添加，清空表单
        this.refresh();
      }
    },
    refresh() {
      this.jobForm = {
        title: "",
        gradeId: "",
        content: "",
      };
    },
    handleConfirm() {
      // 调用父组件传入的确认回调方法，并传递 repoForm 数据
      this.onConfirm(this.jobForm);
      // 关闭对话框
      console.log("jobForm", this.jobForm);
      this.visible = false;
      if (this.editType === 1) {
        // 如果是添加，清空表单
        this.refresh();
      }
    },
    // 失去焦点事件
    onEditorBlur(quill) {},
    // 获得焦点事件
    onEditorFocus(quill) {
      // quill.enable(false);
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      // if (!this.isEdit) {
      //   quill.enable(false)
      // }
      console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },
  },
};
</script>

<style>
.my-quill-editor {
  height: 80%; /* 这里设置为父容器高度的80%，根据实际情况调整 */
}
.ql-editor {
  height: 300px;
}
</style>
